package handler

import (
	"errors"
	"img_analyse/analyse/api/internal/logic"
	"log"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"

	"img_analyse/analyse/api/internal/svc"
	"img_analyse/analyse/api/internal/types"
)

func UploadImageHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 打印日志，确认进入了 Handler
		log.Println("UploadImageHandler - Start")

		// 解析 multipart/form-data
		if err := r.ParseMultipartForm(32 << 20); err != nil {
			httpx.Error(w, err)
			log.Println("Error in ParseMultipartForm:", err)
			return
		}

		// 打印日志，确认表单已经解析
		log.Println("MultipartForm parsed")

		// 获取文件
		files := r.MultipartForm.File["file"]
		if len(files) == 0 {
			httpx.Error(w, errors.New("未获取到上传文件"))
			log.Println("No file found in the request")
			return
		}

		// 取第一个文件
		req := types.ImageUploadRequest{
			File: files[0],
		}

		// 打印日志，确认文件已经正确接收到
		log.Println("File received:", req.File.Filename)

		// 调用逻辑处理
		l := logic.NewUploadImageLogic(r.Context(), svcCtx)
		resp, err := l.UploadImage(&req)
		if err != nil {
			httpx.Error(w, err)
			log.Println("Error in UploadImage:", err)
		} else {
			httpx.OkJson(w, resp)
			log.Println("Image uploaded successfully")
		}
	}
}
